﻿using Microsoft.EntityFrameworkCore;

namespace EMall.Domain
{
    public class EfCoreRepository<TDbContext, TAggregateRoot, TKey> : Repository<TAggregateRoot, TKey>
        where TDbContext : DbContext
        where TAggregateRoot : class, IAggregateRoot<TKey>
    {
        protected TDbContext DbContext;
        protected DbSet<TAggregateRoot> DbSet => DbContext.Set<TAggregateRoot>();
        public EfCoreRepository(TDbContext dbContext)
        {
            ArgumentNullException.ThrowIfNull(dbContext, nameof(dbContext));
            DbContext = dbContext;
        }
        public override async Task AddAsync(TAggregateRoot entity)
        {
            ArgumentNullException.ThrowIfNull(entity, nameof(entity));
            var aaa = await DbSet.AddAsync(entity);
        }
        public override async Task RemoveAsync(TAggregateRoot entity)
        {
            ArgumentNullException.ThrowIfNull(entity, nameof(entity));
            await Task.FromResult(DbSet.Remove(entity));
        }
        public override IQueryable<TAggregateRoot> GetQueryable() => DbSet.AsQueryable();
        public override async Task<int> CountAsync() => await GetQueryable().CountAsync();
        public override async Task<TAggregateRoot> GetAsync(TKey id)
        {
            ArgumentNullException.ThrowIfNull(id, nameof(id));
            return await GetQueryable().FirstOrDefaultAsync(o => o.Id!.Equals(id));
        }
    }
}
